package com.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.common.Result;
import com.blog.pojo.Type;
import com.blog.service.TypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 类型相关
 */
@Slf4j
@RestController
@RequestMapping("/type")
public class TypeController {

    @Autowired
    private TypeService typeService;

    /**
     * 添加分类
     * @param type 类型对象
     * @return Result<String>
     */
    @PostMapping("/save")
    private Result<String> save(@RequestBody Type type){
        LambdaQueryWrapper<Type> typeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        typeLambdaQueryWrapper.eq(Type::getTypeContent,type.getTypeContent());
        Type typeServiceOne = typeService.getOne(typeLambdaQueryWrapper);
        if (typeServiceOne == null){
            typeService.save(type);
            return Result.success("添加成功");
        }else {
            return Result.error("该类型已存在！请勿重复添加");
        }
    }

    /**
     * 条件分页查询
     * @param page 当前页
     * @param pageSize 页面大小
     * @param typeContent 类型名称
     * @return Result<Page>
     */
    @GetMapping("/page")
    private Result<Page> page(int page,int pageSize,String typeContent){
        return Result.success(typeService.page(page,pageSize,typeContent));
    }

    /**
     * 删除单个类型
     * @param typeId 类型id
     * @return Result<String>
     */
    @DeleteMapping("/delete")
    private Result<String> delete(Long typeId){
        boolean flag = typeService.deleteType(typeId);
        if (flag)//该分类下没有其他标签
            return Result.success("删除成功！");
        else//该分类下有标签
            return Result.error("危险操作！请先删除该分类下的所有标签再进行此操作！");
    }

    /**
     * 修改类型
     * @param type 类型对象
     * @return Result<String>
     */
    @PostMapping("/update")
    private Result<String> update(@RequestBody Type type){
        boolean flag = typeService.updateById(type);
        if (flag)
            return Result.success("修改成功！");
        else
            return Result.error("修改失败");
    }

    /**
     * 分类列表
     * @return Result<List<Type>>
     */
    @GetMapping("/list")
    private Result<List<Type>> list(){
        return Result.success(typeService.list());
    }
}
